Zappos = Class.create({
	initialize: function() {
        this.cookie = new Mojo.Model.Cookie("ZapposPreferences");
		this.homeUrl = "http://www.zappos.com";
	},
	
	setSetting: function(field, value) {
		var settings = this.cookie.get();
		settings[field] = value;
		
		this.cookie.put(settings);
	},
	
	getSetting: function(field) {
		var settings = this.cookie.get();

		if (settings == undefined) {
			var settings = {};
			settings["https"] = "Yes";


	    	this.cookie.put(settings);
	    	var settings = this.cookie.get();
        }

        return settings[field];
    },

	search: function(keyword, callback) {
		new Ajax.Request(httpsConnection + this.url + keyword, {
			method: 'get',
			evalJSON: 'false',
			onSuccess: function(searchResult) {
				var responseText = searchResult.responseText;
				var urls = this._getUrls(responseText);

				callback(urls);
			}.bind(this),
		});
	},

	subcategories: function(keyword, callback) {
		new Ajax.Request(this.homeUrl + '/' + keyword.toLowerCase(), {
			method: 'get',
			evalJSON: 'false',
			onSuccess: function(searchResult) {
				var responseText = searchResult.responseText;

				callback(this._getCategories(responseText));
			}.bind(this),
		});
	},

    getProducts: function(departmentCode, path, callback) {
        path = path.toLowerCase();
        departmentCode = departmentCode.toLowerCase();

        path = path.replace('-' + departmentCode, '');


        path = path[1].toUpperCase() + path.substr(2, path.length);
        if (path.indexOf('~') != -1)
        path = path.substring(0, path.indexOf('~'));

        var newPath = '';
        path.split('-').each(function(part) {
            if (newPath != '')
            newPath += '+';

            newPath += part[0].toUpperCase() + part.substr(1, part.length);
        });
        path = newPath;

        var url = this.homeUrl + '/search/'
                    + departmentCode
                    + '/filter/categoryFacet/'
                    + path
                    + '/sort/isNew/desc/productPopularity/asc/';

		new Ajax.Request(url, {
			method: 'get',
			evalJSON: 'false',
			onSuccess: function(searchResult) {
				var responseText = searchResult.responseText;

//                var re = new RegExp('<a\s+href="([^"]+)"\s+class="product[^"]+">(.|\s)+?</a>');
//                var products = re.exec(responseText);

                var begins = responseText.indexOf('searchResults') + 15;
                var ends = responseText.indexOf('<div class="sort bottom"') - 6;
                var products = this._parseForProducts(responseText.substring(begins, ends));

                callback(products);
//				this._getProductsViewAll(url, callback);
			}.bind(this),
		});
    },

    _parseForProducts: function(body) {
        var products = new Array();
        
        var productFound = true;
        while (productFound == true) {
            var begins = body.indexOf('href="') + 6;
            body = body.substring(begins, body.length);
            var ends = body.indexOf('"');
            var url = body.substring(0, ends);
            body = body.substring(ends + 1, body.length);

            var begins = body.indexOf('src="') + 5;
            body = body.substring(begins, body.length);
            var ends = body.indexOf('"');
            var img = body.substring(0, ends);
            body = body.substring(ends + 1, body.length);

            var begins = body.indexOf('class="brandName"') + 18;
            body = body.substring(begins, body.length);
            var ends = body.indexOf('</span>');
            var brandName = body.substring(0, ends);
            body = body.substring(ends + 1, body.length);

            var begins = body.indexOf('class="productName"') + 20;
            body = body.substring(begins, body.length);
            var ends = body.indexOf('</span>');
            var productName = body.substring(0, ends);
            body = body.substring(ends + 1, body.length);

            var begins = body.indexOf('class="price"') + 14;
            body = body.substring(begins, body.length);
            var ends = body.indexOf('</span>');
            var price = body.substring(0, ends);
            body = body.substring(ends + 1, body.length);

            products.push({
                url: url,
                img: img,
                brandName: brandName,
                productName: productName,
                price: price
            });

            if (body.indexOf('href="') == -1)
            productFound = false;
        }

        return products;
    },

    getProduct: function(url, callback) {
        url = this.homeUrl + url;

		new Ajax.Request(url, {
			method: 'get',
			evalJSON: 'false',
			onSuccess: function(searchResult) {
				var responseText = searchResult.responseText;

                begins = responseText.indexOf('productId"') + 10;
                responseText = responseText.substring(begins, responseText.length);
                begins = responseText.indexOf('value="') + 7;
                responseText = responseText.substring(begins, responseText.length);
                begins = responseText.indexOf('"');
                var productId = responseText.substring(0, begins);
                responseText = responseText.substring(begins, responseText.length);

                begins = responseText.indexOf('prDesc') + 8;
                responseText = responseText.substring(begins, responseText.length);

                if (responseText.indexOf('View the') != -1)
                begins = responseText.indexOf('</li>') + 5;
                else
                begins = responseText.indexOf('<ul');

                ends = responseText.indexOf('</ul>');

                if (responseText.indexOf('View the') != -1)
                description = '<ul>' + responseText.substring(begins, ends);
                else
                description = responseText.substring(begins, ends);
                responseText = responseText.substring(ends + 5, responseText.length);
                

                begins = responseText.indexOf('prImage') + 9;
                responseText = responseText.substring(begins, responseText.length);
                begins = responseText.indexOf('src') + 5;
                responseText = responseText.substring(begins, responseText.length);
                ends = responseText.indexOf('"');
                image = responseText.substring(0, ends);
                responseText = responseText.substring(ends + 1, responseText.length);
                
                var product = $H();
                product.set('description', description);
                product.set('image', image);
                product.set('productId', productId);

                callback(product);
			}.bind(this),
		});
    },

    addProductToCart: function(productId) {
		new Ajax.Request(this.homeUrl + '/cartAddItem.do', {
			method: 'get',
			evalJSON: 'false',
            parameters: {
                productId: productId,
                colorId: 42005,
                dimensionValues: 80325,
                dimensionValues: 76828,
                addToCart: '',
                addToCart: ''
            },
			onSuccess: function(searchResult) {
				Mojo.Controller.errorDialog(productId);
			}.bind(this),
		});
    },

    _getProductsViewAll: function(callback) {
		new Ajax.Request(this.homeUrl + path, {
			method: 'get',
			evalJSON: 'false',
			onSuccess: function(searchResult) {
				var responseText = searchResult.responseText;

				callback(this._getProducts(responseText));
			}.bind(this),
		});
    },

	_getCategories: function(body) {
        var results = new Array();

		var continueSearch = true;
		while (continueSearch != false) {
            begins = body.indexOf('<h4>');

            if (begins == -1)
            break;

            body = body.substring(begins + 4, body.length);
            ends = body.indexOf('</h4>');

            h4 = body.substring(0, ends);
            result = h4.stripTags();
            result = result.unescapeHTML();

            if (result.indexOf('More Ways to') == -1
                && (result.indexOf('Shop Clothing') == -1)
                && (result.indexOf('Specialty Sizes') == -1)
                && (result.indexOf('Subscribe') == -1)
                && (result.indexOf('Other Ways') == -1)) {
                var url = h4.substring(h4.indexOf('href="') + 6, h4.indexOf('" >'));
                var resultHash = {
                        'name': result,
                        'url': url
                };

                results.push(resultHash);
            }
		}

        return results;
    },

	_getProducts: function(body) {
        var results = new Array();

		var continueSearch = true;
		while (continueSearch != false) {
            begins = body.indexOf('<h4>');

            if (begins == -1)
            break;

            body = body.substring(begins + 4, body.length);
            ends = body.indexOf('</h4>');

            h4 = body.substring(0, ends);
            result = h4.stripTags();
            result = result.unescapeHTML();

            if (result.indexOf('More Ways to') == -1
                && (result.indexOf('Shop Clothing') == -1)
                && (result.indexOf('Specialty Sizes') == -1)
                && (result.indexOf('Subscribe') == -1)
                && (result.indexOf('Other Ways') == -1)) {
                var url = h4.substring(h4.indexOf('href="') + 6, h4.indexOf('" >'));
                var resultHash = {
                        'name': result,
                        'url': url
                };

                results.push(resultHash);
            }
		}

        return results;
    },
});
